using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
namespace ICSharpCode.TextEditor.Document
{
	public class FileSyntaxModeProvider : ISyntaxModeFileProvider
	{
		private string directory;
		private List<SyntaxMode> syntaxModes;
		public ICollection<SyntaxMode> SyntaxModes
		{
			get
			{
				return this.syntaxModes;
			}
		}
		public FileSyntaxModeProvider(string directory)
		{
			this.directory = directory;
			this.UpdateSyntaxModeList();
		}
		public void UpdateSyntaxModeList()
		{
			string path = Path.Combine(this.directory, "SyntaxModes.xml");
			if (File.Exists(path))
			{
				Stream stream = File.OpenRead(path);
				this.syntaxModes = SyntaxMode.GetSyntaxModes(stream);
				stream.Close();
				return;
			}
			this.syntaxModes = this.ScanDirectory(this.directory);
		}
		public XmlTextReader GetSyntaxModeFile(SyntaxMode syntaxMode)
		{
			string text = Path.Combine(this.directory, syntaxMode.FileName);
			if (!File.Exists(text))
			{
				throw new HighlightingDefinitionInvalidException("Can't load highlighting definition " + text + " (file not found)!");
			}
			return new XmlTextReader(File.OpenRead(text));
		}
		private List<SyntaxMode> ScanDirectory(string directory)
		{
			string[] files = Directory.GetFiles(directory);
			List<SyntaxMode> list = new List<SyntaxMode>();
			string[] array = files;
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i];
				if (Path.GetExtension(text).Equals(".XSHD", StringComparison.OrdinalIgnoreCase))
				{
					XmlTextReader xmlTextReader = new XmlTextReader(text);
					while (xmlTextReader.Read())
					{
						if (xmlTextReader.NodeType == XmlNodeType.Element)
						{
							string name;
							if ((name = xmlTextReader.Name) != null && name == "SyntaxDefinition")
							{
								string attribute = xmlTextReader.GetAttribute("name");
								string attribute2 = xmlTextReader.GetAttribute("extensions");
								list.Add(new SyntaxMode(Path.GetFileName(text), attribute, attribute2));
								break;
							}
							throw new HighlightingDefinitionInvalidException("Unknown root node in syntax highlighting file :" + xmlTextReader.Name);
						}
					}
					xmlTextReader.Close();
				}
			}
			return list;
		}
	}
}
